package com.lc.reader.ui.fragment

import android.app.AlertDialog
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.lc.reader.data.model.Bookmark
import com.lc.reader.data.model.ReadingProgress
import com.lc.reader.databinding.DialogBookmarksBinding
import com.lc.reader.databinding.FragmentReaderBinding
import com.lc.reader.ui.adapter.BookmarkAdapter
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import com.lc.reader.data.repository.BookmarkRepository
import com.lc.reader.di.DependencyContainer

class ReaderFragment : Fragment() {
    
    private var _binding: FragmentReaderBinding? = null
    private val binding get() = _binding!!
    
    // 使用传统的参数获取方式
    private val bookId: Long by lazy {
        arguments?.getLong("bookId", -1L) ?: -1L
    }
    
    private val bookTitle: String by lazy {
        arguments?.getString("bookTitle", "未知书籍") ?: "未知书籍"
    }
    
    private val bookAuthor: String by lazy {
        arguments?.getString("bookAuthor", "未知作者") ?: "未知作者"
    }
    
    private val bookFilePath: String by lazy {
        arguments?.getString("bookFilePath", "") ?: ""
    }
    
    private val bookFormat: String by lazy {
        arguments?.getString("bookFormat", "TXT") ?: "TXT"
    }
    
    // 文本阅读相关变量
    private var fullText: String = ""
    private var currentPage: Int = 0
    private var totalPages: Int = 0
    private var pageSize: Int = 1000 // 每页字符数
    
    // 书签相关
    private val bookmarks = mutableListOf<Bookmark>()
    private lateinit var bookmarkAdapter: BookmarkAdapter
    private lateinit var bookmarkRepository: BookmarkRepository

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentReaderBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 初始化Repository
        bookmarkRepository = DependencyContainer.getBookmarkRepository(requireContext())
        
        setupReader()
        setupClickListeners()
        loadBookContent()
        loadReadingProgress()
        loadBookmarks()
    }
    
    private fun setupReader() {
        // 显示书籍信息
        binding.textTitle.text = bookTitle
        binding.textContent.text = "正在加载书籍内容..."
    }
    
    private fun setupClickListeners() {
        binding.buttonPrev.setOnClickListener {
            goToPreviousPage()
        }
        
        binding.buttonNext.setOnClickListener {
            goToNextPage()
        }
        
        binding.buttonBack.setOnClickListener {
            saveReadingProgress()
            findNavController().navigateUp()
        }
        
        binding.buttonBookmark.setOnClickListener {
            addBookmark()
        }
        
        binding.buttonMore.setOnClickListener {
            showBookmarksDialog()
        }
    }
    
    private fun loadBookContent() {
        if (bookFilePath.isNotEmpty()) {
            // 异步加载文件内容
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val content = loadTextFile(requireContext(), Uri.parse(bookFilePath))
                    withContext(Dispatchers.Main) {
                        if (content.isNotEmpty()) {
                            fullText = content
                            totalPages = (fullText.length + pageSize - 1) / pageSize
                            displayCurrentPage()
                        } else {
                            binding.textContent.text = "无法读取文件内容"
                        }
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        binding.textContent.text = "读取文件失败: ${e.message}"
                    }
                }
            }
        } else {
            binding.textContent.text = "文件路径无效"
        }
    }
    
    private fun loadTextFile(context: Context, uri: Uri): String {
        val stringBuilder = StringBuilder()
        context.contentResolver.openInputStream(uri)?.use { inputStream ->
            BufferedReader(InputStreamReader(inputStream, "UTF-8")).use { reader ->
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    stringBuilder.append(line).append("\n")
                }
            }
        }
        return stringBuilder.toString()
    }
    
    private fun displayCurrentPage() {
        if (fullText.isEmpty()) return
        
        val startIndex = currentPage * pageSize
        val endIndex = minOf(startIndex + pageSize, fullText.length)
        val pageContent = fullText.substring(startIndex, endIndex)
        
        binding.textContent.text = pageContent
        
        // 更新页码信息
        binding.textPageInfo.text = "第${currentPage + 1}页 / 共${totalPages}页"
        
        // 更新按钮状态
        binding.buttonPrev.isEnabled = currentPage > 0
        binding.buttonNext.isEnabled = currentPage < totalPages - 1
    }
    
    private fun goToPreviousPage() {
        if (currentPage > 0) {
            currentPage--
            displayCurrentPage()
            saveReadingProgress()
        }
    }
    
    private fun goToNextPage() {
        if (currentPage < totalPages - 1) {
            currentPage++
            displayCurrentPage()
            saveReadingProgress()
        }
    }
    
    private fun addBookmark() {
        val editText = EditText(requireContext()).apply {
            hint = "输入书签描述"
            setText("第${currentPage + 1}页")
        }
        
        AlertDialog.Builder(requireContext())
            .setTitle("添加书签")
            .setView(editText)
            .setPositiveButton("确定") { _, _ ->
                val description = editText.text.toString()
                if (description.isNotEmpty()) {
                    val bookmark = Bookmark(
                        bookId = bookId,
                        pageNumber = currentPage,
                        description = description
                    )
                    bookmarks.add(bookmark)
                    saveBookmark(bookmark)
                    Snackbar.make(binding.root, "书签添加成功", Snackbar.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun showBookmarksDialog() {
        val dialogBinding = DialogBookmarksBinding.inflate(layoutInflater)
        
        // 设置书签列表
        bookmarkAdapter = BookmarkAdapter { bookmark ->
            currentPage = bookmark.pageNumber
            displayCurrentPage()
            saveReadingProgress()
        }
        
        dialogBinding.recyclerViewBookmarks.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = bookmarkAdapter
        }
        
        bookmarkAdapter.submitList(bookmarks.toList())
        
        val dialog = AlertDialog.Builder(requireContext())
            .setView(dialogBinding.root)
            .create()
        
        // 设置按钮点击事件
        dialogBinding.buttonFromBeginning.setOnClickListener {
            currentPage = 0
            displayCurrentPage()
            saveReadingProgress()
            dialog.dismiss()
        }
        
        dialogBinding.buttonContinue.setOnClickListener {
            // 继续上次阅读位置，不需要改变currentPage
            dialog.dismiss()
        }
        
        dialog.show()
    }
    
    private fun loadReadingProgress() {
        // 从SharedPreferences加载阅读进度
        val sharedPrefs = requireContext().getSharedPreferences("reading_progress", Context.MODE_PRIVATE)
        currentPage = sharedPrefs.getInt("book_${bookId}_page", 0)
    }
    
    private fun saveReadingProgress() {
        // 保存阅读进度到SharedPreferences
        val sharedPrefs = requireContext().getSharedPreferences("reading_progress", Context.MODE_PRIVATE)
        sharedPrefs.edit().apply {
            putInt("book_${bookId}_page", currentPage)
            putLong("book_${bookId}_time", System.currentTimeMillis())
            apply()
        }
    }
    
    private fun loadBookmarks() {
        // 从SharedPreferences加载书签
        val sharedPrefs = requireContext().getSharedPreferences("bookmarks", Context.MODE_PRIVATE)
        val bookmarksJson = sharedPrefs.getString("book_${bookId}", "[]")
        // 这里简化处理，实际应该使用JSON解析
        // 暂时使用空列表
    }
    
    private fun saveBookmark(bookmark: Bookmark) {
        // 保存书签到SharedPreferences
        val sharedPrefs = requireContext().getSharedPreferences("bookmarks", Context.MODE_PRIVATE)
        // 这里简化处理，实际应该使用JSON序列化
        // 暂时只保存到内存中
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        saveReadingProgress()
        _binding = null
    }
}
